﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.ApplicationModel.Contacts;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;

// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=391641

namespace DialExpress
{
    /// <summary>
    /// An empty page that can be used on its own or navigated to within a Frame.
    /// </summary>
    public sealed partial class MainPage : Page
    {
        public MainPage()
        {
            this.InitializeComponent();

            this.NavigationCacheMode = NavigationCacheMode.Required;
        }

        /// <summary>
        /// Invoked when this page is about to be displayed in a Frame.
        /// </summary>
        /// <param name="e">Event data that describes how this page was reached.
        /// This parameter is typically used to configure the page.</param>
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            // TODO: Prepare page for display here.
            tbSearch.Text = "";
            FindContacts(string.Empty);

            // TODO: If your application contains multiple pages, ensure that you are
            // handling the hardware Back button by registering for the
            // Windows.Phone.UI.Input.HardwareButtons.BackPressed event.
            // If you are using the NavigationHelper provided by some templates,
            // this event is handled for you.
        }

        private async void FindContacts(string searchText)
        {
            ContactStore contactStore = await ContactManager.RequestStoreAsync();

            IReadOnlyList<Contact> contacts = null;

            if (String.IsNullOrEmpty(searchText))
            {
                // Find all contacts
                contacts = await contactStore.FindContactsAsync();
            }
            else
            {
                // Find contacts based on a search string
                contacts = await contactStore.FindContactsAsync(searchText);
            }

            var listItem = new List<ContactItem>();
            foreach (var contact in contacts.Where(x=>x.Phones.Any()))
            {
                listItem.Add(new ContactItem
                {
                    Id = contact.Id,
                    Name = contact.DisplayName,
                    Phone = contact.Phones.First().Number
                });
            }
            lvContactList.ItemsSource = listItem;
        }

        private async void FindAndCall(string searchText)
        {
            ContactStore contactStore = await ContactManager.RequestStoreAsync();

            IReadOnlyList<Contact> contacts = null;

            if (!String.IsNullOrEmpty(searchText))
            {
                // Find contacts based on a search string
                contacts = await contactStore.FindContactsAsync(searchText);

                if (contacts.Any())
                {
                    var contact = contacts.First();

                    Windows.ApplicationModel.Calls.PhoneCallManager.ShowPhoneCallUI(contact.Phones.First().Number, contact.DisplayName);
                }
            }
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            FindContacts(tbSearch.Text);
        }

        private void lvContactList_ItemClick(object sender, ItemClickEventArgs e)
        {
            var itemSelected = sender.ToString();
        }

        private void lvContactList_Tapped(object sender, TappedRoutedEventArgs e)
        {
            var itemSelected = (ContactItem)lvContactList.SelectedItem;
            if (itemSelected != null)
            {
                Windows.ApplicationModel.Calls.PhoneCallManager.ShowPhoneCallUI(itemSelected.Phone, itemSelected.Name);
            }
        }
    }

    public class ContactItem
    {
        public string Id { get; set; }

        public string Name { get; set; }

        public string Phone { get; set; }
    }
}
